<template>
	<n-modal v-model:show="modalVisible" preset="card" :title="title" class="w-700px">
		<n-form ref="formRef" label-placement="left" require-mark-placement="right-hanging" :label-width="80"
						:model="formModel">
			<n-form-item :span="12" label="上级部门" path="parentId">
				<n-tree-select
					:options="options"
					:value="formModel.parentId"
					label-field="name"
					key-field="id"
					@update:value="handleUpdateValue"
					clearable
				/>
			</n-form-item>

			<n-form-item :span="12" label="部门名称" path="deptName">
				<n-input v-model:value="formModel.deptName" clearable/>
			</n-form-item>
			<n-form-item :span="12" label="排序" path="weight">
				<n-input-number v-model:value="formModel.weight" clearable/>
			</n-form-item>
			<n-space class="w-full pt-16px" :size="24" justify="end">
				<n-button class="w-72px" @click="modalVisible=false">取消</n-button>
				<n-button class="w-72px" type="primary" @click="handleSubmit">确定</n-button>
			</n-space>
		</n-form>
	</n-modal>
</template>

<script setup>

import {reactive, toRefs, onMounted} from 'vue';
import {getDeptTableTree, saveOrUpdateDept} from '@/service';
import {useMessage} from 'naive-ui'

const msg = useMessage()

const emit = defineEmits(['fetch-data'])
const props=defineProps({
	initSelectData: []
})
const state = reactive({
	modalVisible: false,
	formModel: {},
	title: '新增',
	options: [],
	saveOrUpdateState: 'add',
	tableData: []
})

const
	{
		modalVisible,
		formModel,
		title,
		options,
	} = toRefs(state)


const saveDept = (row) => {
	state.title = '新增'
	state.saveOrUpdateState = 'add'
	state.modalVisible = true;
	state.options = props.initSelectData
	state.formModel = {};
	// 选中
	if (row) {
		state.formModel.parentId = row.id;
	}
}
const editDept = (row) => {
	state.title = '编辑'
	state.saveOrUpdateState = 'update'
	state.modalVisible = true;
	state.options = props.initSelectData
	state.formModel.deptId = row.id;
	state.formModel.weight = row.weight;
	state.formModel.parentId = row.parentId
	state.formModel.deptName = row.name;
}


const handleUpdateValue = (value, option) => {
	state.formModel.parentId = value;
}

const handleSubmit = async () => {
	let row = {
		...state.formModel,
		parentId: state.formModel.parentId || '-1'
	};
	const {data} = await saveOrUpdateDept(row, state.saveOrUpdateState);
	if (!data) {
		msg.error("处理失败")
	} else {
		msg.success("处理成功");
	}
	emit('fetch-data');
	state.modalVisible = false;
}


defineExpose({
	saveDept,
	editDept
})


</script>

<style scoped>

</style>
